package com.yipao.wx.web.order;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.google.common.collect.Lists;
import com.yipao.db.constant.DbConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 微信小程序推送
 * 微信公众平台>设置>安全中心>ip白名单
 *
 * @author tianhao
 * @date 2020/05/14
 * @see '发送订阅信息' 'https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html'
 */
@Service
@Slf4j
public class WxMinAppPushService {
    @Resource
    private WxMaService wxMaService;

    /**
     * 模板id 取货通知
     */
    private String PICK_UP_TEMPLATE_ID = "l89dW_AmNMvxTmtUcMEN0hMfg1s5ezyFWrU9DZteRjc";

    /**
     * 取货通知
     *
     * @param openId
     * @param productName   商品信息,多个商品用逗号隔开,最多30个字符
     * @param pickUpCode    取货码
     * @param deviceNo      设备编号
     * @param deviceAddress 设备地址
     * @param prop          温馨提示
     */
    public void pushOrderDelivery(String openId, String productName, String pickUpCode,
                                  String deviceNo, String deviceAddress, String prop) {
        if (productName.length() > DbConstant.PRODUCT_NAME_MAX_LEN) {
            productName = productName.substring(0, DbConstant.PRODUCT_NAME_MAX_LEN) + "...";
        }
        try {
            WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
                    .toUser(openId)
                    .page("/pages/index/index")
                    .data(Lists.newArrayList(
                            // 商品名称
                            new WxMaSubscribeMessage.Data("keyword1", productName),
                            // 取货码
                            new WxMaSubscribeMessage.Data("keyword2", pickUpCode),
                            // 设备编码
                            new WxMaSubscribeMessage.Data("keyword3", deviceNo),
                            // 设备编号
                            new WxMaSubscribeMessage.Data("keyword3", deviceAddress),
                            // 备注
                            new WxMaSubscribeMessage.Data("keyword4", prop)

                    ))
                    .templateId(PICK_UP_TEMPLATE_ID)
                    .build();
            this.wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
        } catch (Exception e) {
            log.error("发送取货通知异常", e);
        }
    }
}
